import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CpuUsage
{
    private int BeginProcStatUser;
    private int BeginProcStatNiced;
    private int BeginProcStatSystem; 
    
    public CpuUsage( int coreNumber )
    {	SetBeginProcStatValues( ReadProcStatValues( coreNumber ) );    }

    public int[] ReadProcStatValues( int coreNumber )
    {
        int[] ProcStatOutput = new int[3];
        
    	String ProcStatFile = "/proc/stat";

        	try 
        	{    	BufferedReader in = new BufferedReader(new FileReader( ProcStatFile )); 

        		String strLine;
        	
        		while ((strLine = in.readLine()) != null)
        		{	Pattern pattern = Pattern.compile("^cpu" + coreNumber + "\\s+(\\d+)\\s+(\\d+)\\s+(\\d+).*");
        			Matcher matcher = pattern.matcher( strLine );

        			while (matcher.find())
        			{	ProcStatOutput[0] = Integer.parseInt(matcher.group(1));	
        				ProcStatOutput[1] = Integer.parseInt(matcher.group(2));
        				ProcStatOutput[2] = Integer.parseInt(matcher.group(3));	}
        		}
        	}
        	catch ( Exception e ) 
        	{    e.printStackTrace();	}
        	
        return ProcStatOutput;
    }
    
    public int GetProcStatDiffAgregated( int[] UserNicedSystem )
    {	return UserNicedSystem[0] + UserNicedSystem[1] + UserNicedSystem[2];        }
    
    public int[] GetProcStatDiff( int coreNumber )
    {
	int[] ProcStatNOW = ReadProcStatValues( coreNumber );
        int[] ProcStatOutput = new int[3];
        
        ProcStatOutput[0] = ProcStatNOW[0] - BeginProcStatUser;
        ProcStatOutput[1] = ProcStatNOW[1] - BeginProcStatNiced;
        ProcStatOutput[2] = ProcStatNOW[2] - BeginProcStatSystem;
        
        return ProcStatOutput;
    }
    
    public void SetBeginProcStatValues( int[] values )
    {   BeginProcStatUser = values[0]; 
        BeginProcStatNiced = values[1];
        BeginProcStatSystem = values[2];        }



}
